/**
 * create by young (young2f@outlook.com) on 2020/2/27
 */
'use strict';
import _ from 'lodash'
const uuid = require('node-uuid');
const fs=require('fs');

async function writeFile(file, content) {
  if (typeof content === 'object') {
    content = JSON.stringify(content);
  }
  return fs.writeFileSync(file, content);
}
async function readFile2json(file) {
  if (!fs.existsSync(file)) {
    console.error('readFile2json,file isnot exist', file);
    return;
  }

  const str = await fs.readFileSync(file, 'utf8');
  return str2json(str);
}

function str2json(str) {
  try {
    if (typeof str === 'object') {
      return str;
    }
    if (typeof str === 'array') {
      return str;
    }
    if (str === undefined || str === null || str === '') {
      console.error('str2json error:str is null');
      return;
    }
    const key = '{\\';
    if (str.startsWith(key)) {
      str = str.replace(/[\\]/g, '');
    }
    let json = JSON.parse(str);

    if (typeof json === 'string') {
      json = eval('(' + json + ')');
      return str2json(json);
    }
    return json;
  } catch (e) {
    console.error('str2json error', str, e);
    return;
  }
}
 function replaceArray(arr, key, newval) {
  var match = _.find(arr, key);
  if(match){
    var index = _.indexOf(arr, _.find(arr, key));
    arr.splice(index, 1, newval);
  } else {
    arr.push(newval);
  }
};
function getRandom(size) {
  return Math.ceil(Math.random() * size);
}

function getUUID(size) {
  let id = uuid.v4();
  id.replace(/\-/g, '');
  return id.slice(0,size).toUpperCase();
}

//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
      break;
    default:
      return 0;
      break;
  }
}

module.exports = {
  randomNum,
  getRandom,
  getUUID,
  writeFile,
  readFile2json,
  replaceArray
}
